<template>
	<a-card title="审核房源" :body-style="{ padding: '0' }">
		<!-- 房源列表表格 -->
		<a-table :columns="columns" :data-source="houses" :pagination="false" :row-key="(record) => record.id" bordered>
			<template #bodyCell="{ column, record }">
				<!-- 房源图片（取第一张） -->
				<template v-if="column.key === 'houseImage'">
					<img
						:src="record.houseImages && record.houseImages.length ? record.houseImages[0] : ''"
						alt="房源图片"
						style="width: 120px; height: 100px; object-fit: cover"
					/>
				</template>
				<!-- 房源地址 -->
				<template v-else-if="column.key === 'address'">
					{{ record.address }}
				</template>
				<!-- 房东姓名 -->
				<template v-else-if="column.key === 'landlordName'">
					{{ record.landlordName }}
				</template>
				<!-- 房东电话 -->
				<template v-else-if="column.key === 'landlordPhone'">
					{{ record.landlordPhone }}
				</template>
				<!-- 操作列 -->
				<template v-else-if="column.key === 'action'">
					<a @click="openAuditModal(record)">详情</a>
				</template>
				<!-- 默认展示 -->
				<template v-else>
					{{ record[column.dataIndex] }}
				</template>
			</template>
		</a-table>

		<!-- 分页器 -->
		<a-pagination
			class="pagination"
			:current="pagination.current"
			:page-size="pagination.pageSize"
			:total="pagination.total"
			:page-size-options="['5', '10', '20', '50']"
			@change="handlePageChange"
			@showSizeChange="handlePageSizeChange"
			:show-total="(total, range) => `${range[0]}-${range[1]} 共 ${total} 条`"
			:locale="{ items_per_page: '条/页' }"
		></a-pagination>

		<!-- 审核详情 Modal -->
		<a-modal
			v-model:visible="auditModalVisible"
			title="审核房源详情"
			:width="1000"
			:confirmLoading="auditConfirmLoading"
			@ok="submitAudit"
			@cancel="cancelAudit"
			ok-text="确认审核"
			cancel-text="取消"
		>
			<!-- 详情区域：使用 Form 展示房源所有信息（只读） -->
			<a-form layout="vertical">
				<!-- 第一行：房源标题、小区、楼层 -->
				<a-row :gutter="24">
					<a-col :span="8">
						<a-form-item label="房源标题">
							<a-input v-model:value="auditForm.title" disabled />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="小区">
							<a-input v-model:value="auditForm.community" disabled />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="楼层">
							<a-input-number v-model:value="auditForm.floor" disabled style="width: 100%" />
						</a-form-item>
					</a-col>
				</a-row>
				<!-- 第二行：地区、详细地址 -->
				<a-row :gutter="24">
					<a-col :span="8">
						<a-form-item label="详细地址">
							<a-input v-model:value="auditForm.address" disabled />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="房型">
							<a-input v-model:value="auditForm.houseType" disabled />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="配套设施">
							<a-textarea v-model:value="auditForm.facilities" disabled :auto-size="{ minRows: 1, maxRows: 5 }" />
						</a-form-item>
					</a-col>
				</a-row>
				<!-- 第三行：房源描述 -->
				<a-row :gutter="24">
					<a-col :span="24">
						<a-form-item label="房源描述">
							<a-textarea v-model:value="auditForm.description" disabled :rows="3" />
						</a-form-item>
					</a-col>
				</a-row>
				<!-- 第四行：房型、租金 -->
				<a-row :gutter="24">
					<a-col :span="6">
						<a-form-item label="面积">
							<a-input-number v-model:value="auditForm.area" disabled style="width: 100%" />
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="租金">
							<a-input-number v-model:value="auditForm.price" disabled style="width: 100%" />
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="租期">
							<a-input v-model:value="auditForm.lease" disabled />
						</a-form-item>
					</a-col>
					<a-col :span="6">
						<a-form-item label="支付方式">
							<a-input v-model:value="auditForm.payType" disabled />
						</a-form-item>
					</a-col>
				</a-row>
				<!-- 第六行：配套设施、所属商圈、附近地铁站、步行时间 -->
				<a-row :gutter="24">
					<a-col :span="8">
						<a-form-item label="所属商圈">
							<a-input v-model:value="auditForm.businessArea" disabled />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="附近地铁站">
							<a-input v-model:value="auditForm.subwayStation" disabled />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item label="步行到地铁站时间（分钟）">
							<a-input-number v-model:value="auditForm.traffic" disabled style="width: 100%" />
						</a-form-item>
					</a-col>
				</a-row>
				<!-- 第七行：房源图片展示（全部图片） -->
				<a-row :gutter="24">
					<a-col :span="24">
						<a-form-item label="房源图片">
							<div>
								<a-image
									v-for="(img, index) in auditForm.houseImages"
									:key="index"
									:src="img"
									alt="房源图片"
									style="width: 120px; height: 100px; object-fit: cover; margin-right: 1rem"
								/>
							</div>
						</a-form-item>
					</a-col>
				</a-row>

				<a-col :span="24">
					<a-form-item label="产权证明（仅支持PDF文件）">
							<a-button type="primary" v-if="auditForm.titleDeed" @click="previewTitleDeed"
							>预览当前产权证明
							</a-button>
					</a-form-item>
				</a-col>

				<!-- 审核操作区域 -->
				<a-divider>请选择审核结果</a-divider>
				<a-form-item label="审核结果">
					<a-radio-group v-model:value="auditDecision">
						<a-radio value="approved">同意</a-radio>
						<a-radio value="rejected" style="margin-left: 1rem">拒绝</a-radio>
					</a-radio-group>
				</a-form-item>
				<a-form-item v-if="auditDecision === 'rejected'" label="拒绝理由">
					<a-textarea v-model:value="auditRemarks" placeholder="请输入拒绝理由" :rows="3" />
				</a-form-item>
			</a-form>
		</a-modal>
	</a-card>
</template>

<script setup>
	import { ref, reactive, computed, onMounted, nextTick } from 'vue';
	import { message, Modal } from 'ant-design-vue';
	import adminApi from '@/api/adminApi'; // 此处假设审核接口由 adminApi 实现

	// -------------------- 列表和分页 --------------------
	const houses = ref([]); // 后端返回的所有房源数据
	const pagination = reactive({
		current: 1,
		pageSize: 4,
		total: 0
	});

	// 表格列配置（展示核心字段）
	const columns = [
		{ title: '房源图片', dataIndex: 'houseImages', key: 'houseImage', width: 120 },
		{ title: '房源地址', dataIndex: 'address', key: 'address' },
		{ title: '房东姓名', dataIndex: 'landlordName', key: 'landlordName' },
		{ title: '房东电话', dataIndex: 'landlordPhone', key: 'landlordPhone' },
		{ title: '操作', dataIndex: 'action', key: 'action', width: 150 }
	];

	// 加载待审核房源数据
	const loadHouses = () => {
		// 这里使用 adminApi.getPendingHouses 接口，返回的数据中每项包含
		// 房源图片列表（houseImages）、地址、房东姓名、房东电话、备注等字段
		adminApi
			.getPendingHouses(pagination.current, pagination.pageSize)
			.then((res) => {
				if (res.code === 200) {
					houses.value = res.data.houses;
					pagination.total = res.data.total;
				} else {
					message.error(res.message || '查询失败');
				}
			})
			.catch(() => {
				message.error('获取房源数据失败');
			});
	};

	const handlePageChange = (page) => {
		pagination.current = page;
		loadHouses();
	};
	const handlePageSizeChange = (current, size) => {
		pagination.pageSize = size;
		pagination.current = 1;
		loadHouses();
	};

	// -------------------- 审核 Modal 相关 --------------------
	const auditModalVisible = ref(false);
	const auditConfirmLoading = ref(false);
	// 用于在审核 Modal 中展示房源详情及审核操作
	const auditForm = reactive({
		id: null,
		title: '',
		community: '',
		floor: null,
		address: '',
		description: '',
		houseType: '',
		price: null,
		lease: '',
		area:'',
		payType: '',
		facilities: '',
		businessArea: '',
		subwayStation: '',
		traffic: null,
		longitude: '',
		latitude: '',
		remarks: '',
		houseStatus: '',
		houseImages: [], // 房源图片列表
		landlordName: '',
		landlordPhone: '',
		titleDeed: '', // 新增产权证明URL字段
	});

	// 记录审核决策和拒绝理由
	const auditDecision = ref('');
	const auditRemarks = ref('');

	// 点击“详情”按钮时，打开审核 Modal并回显房源详情
	const openAuditModal = (record) => {
		// 先调用 tryLockHouse 接口，传入房源 ID
		adminApi.tryLockHouse(record.id)
			.then(res => {
				if (res.code === 200 && res.data === true) {
					// 锁定成功，打开审核 Modal
					auditModalVisible.value = true;
					// 将 record 数据复制到 auditForm 中以便回显房源详情
					Object.assign(auditForm, record);
					// 清空审核决策和拒绝理由
					auditDecision.value = '';
					auditRemarks.value = '';
				} else {
					message.info('该房源已被其他管理员锁定，请刷新列表');
					loadHouses();
				}
			})
			.catch(() => {
				message.error('获取房源详情失败，请重试');
			});
	};



	// 审核确认提交
	const submitAudit = () => {
		if (!auditDecision.value) {
			message.error('请选择审核结果');
			return;
		}
		if (auditDecision.value === 'rejected' && (!auditRemarks.value || auditRemarks.value.trim() === '')) {
			message.error('请填写拒绝理由');
			return;
		}
		Modal.confirm({
			title: '确认审核该房源吗？',
			okText: '确认',
			cancelText: '取消',
			onOk() {
				auditConfirmLoading.value = true;
				// 如果审核结果为 approved，则备注默认为“审核通过”，否则使用用户输入的拒绝理由
				const newStatus = auditDecision.value === 'approved' ? 'approved' : 'rejected';
				const remarks = auditDecision.value === 'approved' ? '审核通过' : auditRemarks.value;
				adminApi.auditHouse({
					houseId: auditForm.id,
					newStatus,
					remarks
				})
					.then(res => {
						auditConfirmLoading.value = false;
						if (res.code === 200) {
							message.success('审核成功');
							auditModalVisible.value = false;
							loadHouses();
						} else if (res.code === 409) {
							// 冲突，提示并自动刷新列表
							message.info('该房源已被其他管理员审核，页面已自动刷新');
							loadHouses();
						} else {
							message.error(res.message || '审核失败');
						}
					})
					.catch(() => {
						auditConfirmLoading.value = false;
						message.error('审核失败，请重试');
					});

			}
		});
	};

	const cancelAudit = () => {
		auditModalVisible.value = false;
	};

	// 新增预览逻辑
	const previewTitleDeed = () => {
		window.open(auditForm.titleDeed, '_blank'); // 打开预览页面
	};

	onMounted(() => {
		loadHouses();
	});
</script>

<style scoped>
	.select-container {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		margin-bottom: 1rem;
		font-size: 15px;
	}

	/* 此处筛选已去除，可根据需要删除该样式 */
	.pagination {
		margin-top: 1rem;
		text-align: right;
	}
</style>
